package com.fezs.web.mvc.config;

import com.fezs.web.mvc.aop.ControllerAop;
import com.fezs.web.mvc.enums.WebFilterOrderEnum;
import com.fezs.web.mvc.handle.GlobalExceptionController;
import com.fezs.web.mvc.handle.GlobalExceptionHandler;
import com.fezs.web.mvc.interceptor.TraceIdInterceptor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.Filter;

/**
 * @author zhukai
 * @since 2022/8/18
 */
@Configuration(proxyBeanMethods = false)
public class MvcConfig implements WebMvcConfigurer {

    @Bean
    public ControllerAop controllerAop() {
        return new ControllerAop();
    }

    @Bean
    public GlobalExceptionHandler globalExceptionHandler() {
        return new GlobalExceptionHandler();
    }

    @Bean
    public GlobalExceptionController globalExceptionController() {
        return new GlobalExceptionController();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // traceId
        registry.addInterceptor(new TraceIdInterceptor());
    }

    /**
     * 创建 CorsFilter Bean，解决跨域问题
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterBean() {
        // 创建 CorsConfiguration 对象
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern(CorsConfiguration.ALL); // 设置访问源地址
        config.addAllowedHeader(CorsConfiguration.ALL); // 设置访问源请求头
        config.addAllowedMethod(CorsConfiguration.ALL); // 设置访问源请求方法
        // 创建 UrlBasedCorsConfigurationSource 对象
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config); // 对接口配置跨域设置
        return createFilterBean(new CorsFilter(source), WebFilterOrderEnum.CORS_FILTER);
    }

    private static <T extends Filter> FilterRegistrationBean<T> createFilterBean(T filter, Integer order) {
        FilterRegistrationBean<T> bean = new FilterRegistrationBean<>(filter);
        bean.setOrder(order);
        return bean;
    }
}
